import 'package:bruno/bruno.dart';
import 'package:common/common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:miaowu/app/common/window_pop/public_btn_tem.dart';
import 'package:miaowu/app/common/window_pop/public_btn_widget.dart';
import 'package:miaowu/app/module/mine/money/member_vip/member_agreement_widget.dart';
import 'package:miaowu/app/module/mine/money/member_vip/member_pay_widget.dart';

import 'wallet_config.dart';
import 'wallet_help_widget.dart';

class WalletPage extends StatefulWidget {
  const WalletPage({super.key});

  @override
  State<WalletPage> createState() => _WalletPageState();
}

class _WalletPageState extends State<WalletPage> {
  WalletConfigData? walletConfig;
  bool isChecked = false;
  CoinOptions? chooseCoinOptions;
  PublicBtnItem? coinLogsItem;
  PublicBtnItem? helpCoinItem;

  @override
  void initState() {
    super.initState();
    fetchRechConfig();
  }

  void fetchRechConfig() {
    HttpProvider.get(
      '/rech/index',
      explain: '充值首页（钱包首页）',
      success: (result) {
        WalletConfigData config = WalletConfigData.fromJson(result.data);
        walletConfig = config;

        helpCoinItem = config.sec1?.btns?.first;

        for (PublicBtnItem element in config.sec1?.btns ?? []) {
          if (element.key == 'coinLogs') {
            coinLogsItem = element;
          }
          if (element.key == 'helpCoin') {
            helpCoinItem = element;
          }
        }
        setState(() {});
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Image.asset('assets/app/images/member/wallet_top_bg.png', width: AppScreen.width, fit: BoxFit.cover),
        Scaffold(
          appBar: BrnAppBar(
              title: const Text('金币余额', style: TextStyle(color: Colors.white)),
              backgroundColor: Colors.transparent,
              actions: [
                if (helpCoinItem != null)
                  PublicButtonWidget(
                      btnItem: helpCoinItem!,
                      ignoreKey: 'helpCoin',
                      child: Image.asset('assets/app/images/member/wallet_tips_icon.png', width: 22),
                      alertCallBack: (WindowBtn windowBtn) {},
                      clickAction: (PublicBtnItem btnItem) {
                        showModalBottomSheet(
                            context: context,
                            builder: (_) {
                              return WalletHelpWidget(helpCoinItem: btnItem);
                            });
                      }),
                if (coinLogsItem != null)
                  PublicButtonWidget(
                    btnItem: coinLogsItem!,
                    child: Image.asset('assets/app/images/member/wallet_history.png', width: 32),
                    alertCallBack: (WindowBtn windowBtn) {},
                  ),
                const SizedBox()
              ],
              systemOverlayStyle: const SystemUiOverlayStyle(statusBarColor: Colors.white)),
          backgroundColor: Colors.transparent,
          body: walletConfig == null
              ? const Center(child: CupertinoActivityIndicator())
              : Container(
                  padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 12),
                  color: Colors.transparent,
                  child: CustomScrollView(
                    slivers: [
                      if (walletConfig?.sec1?.view == 1) SliverToBoxAdapter(child: _buildMemberInfoWarpper()),
                      if (walletConfig?.sec2?.view == 1) _buildMemberVipOptionsWarpper(),
                      // if (walletConfig?.sec3?.view == 1) _buildMemberVipFlagsHeaderWarpper(),
                      // if (walletConfig?.sec3?.view == 1) _buildMemberVipFlagsWarpper(),
                      // if (walletConfig?.sec3?.view == 1) _buildMemberVipFlagsFooterWarpper()
                    ],
                  ),
                ),
          bottomNavigationBar: walletConfig?.sec5 != null
              ? Container(
                  height: 140 + AppScreen.safeAreaPaddingBottom,
                  decoration: BoxDecoration(
                      color: const Color(0xFF212121),
                      borderRadius: BorderRadius.only(topLeft: Radius.circular(16.r), topRight: Radius.circular(16.r))),
                  padding: EdgeInsets.only(bottom: AppScreen.safeAreaPaddingBottom),
                  child: Column(
                    children: [
                      Container(
                        height: 51,
                        margin: const EdgeInsets.only(left: 20, right: 20, top: 20),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            gradient: const LinearGradient(
                                colors: [Color(0xFFFFD06A), Color(0xFFFFA851)],
                                begin: Alignment.centerRight,
                                end: Alignment.centerLeft),
                            borderRadius: BorderRadius.circular(25)),
                        child: Text(
                          chooseCoinOptions == null ? "确认协议并支付" : "确认协议并支付 ${chooseCoinOptions!.priceStr}",
                          style: TextStyle(color: Colors.white, fontSize: 16.sp, fontWeight: FontWeight.w600),
                        ),
                      ).onTap(() {
                        if (chooseCoinOptions == null) {
                          return;
                        }
                        if (!isChecked) {
                          Toast.showText('请同意协议');
                          return;
                        }
                        showModalBottomSheet(
                            context: context,
                            builder: (_) {
                              return MemberPayWidget(
                                sec41: walletConfig!.sec41!,
                                price: chooseCoinOptions!.priceStr ?? '',
                              );
                            });
                      }),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 32),
                        child: MemberAgreementWidget(
                            title: walletConfig!.sec5!.title ?? "",
                            config: walletConfig!.sec5!.btns!.first,
                            isChecked: isChecked,
                            onChecked: () {
                              isChecked = !isChecked;
                              setState(() {});
                            }),
                      )
                    ],
                  ),
                )
              : const SizedBox(),
        ),
      ],
    );
  }

  // SliverToBoxAdapter _buildMemberVipFlagsFooterWarpper() {
  //   return SliverToBoxAdapter(
  //     child: Container(
  //       decoration: BoxDecoration(
  //           color: const Color(0xFF212121),
  //           borderRadius: BorderRadius.only(bottomLeft: Radius.circular(16.r), bottomRight: Radius.circular(16.r))),
  //       height: 16.h,
  //     ),
  //   );
  // }

  // SliverToBoxAdapter _buildMemberVipFlagsHeaderWarpper() {
  //   return SliverToBoxAdapter(
  //     child: Column(
  //       children: [
  //         const SizedBox(height: 20),
  //         Image.asset('assets/app/images/member/member_herder.png'),
  //         Container(
  //           decoration: const BoxDecoration(color: Color(0xFF212121)),
  //           height: 60.h,
  //           child: Container(
  //             padding: EdgeInsets.symmetric(horizontal: 16.w),
  //             child: Row(
  //               mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //               children: [
  //                 Text('会员权益',
  //                     style: TextStyle(fontSize: 14.sp, color: const Color(0xFFD6B587), fontWeight: FontWeight.w600)),
  //                 Text('普通用户',
  //                     style: TextStyle(fontSize: 14.sp, color: const Color(0xFFD6B587), fontWeight: FontWeight.w600)),
  //                 Text('会员用户',
  //                     style: TextStyle(fontSize: 14.sp, color: const Color(0xFFD6B587), fontWeight: FontWeight.w600))
  //               ],
  //             ),
  //           ),
  //         ),
  //       ],
  //     ),
  //   );
  // }

  SliverList _buildMemberVipOptionsWarpper() {
    return SliverList.builder(
      itemBuilder: (BuildContext context, int index) {
        CoinOptions coinOptions = walletConfig!.sec2!.coinOptions![index];
        return Stack(
          children: [
            Container(
              margin: EdgeInsets.symmetric(vertical: 7.h),
              decoration: BoxDecoration(
                  color: const Color(0xFF212121),
                  borderRadius: BorderRadius.circular(16.w),
                  border: chooseCoinOptions != null
                      ? Border.all(
                          color: const Color(0xFFEDA47E),
                          width: coinOptions.rechid == chooseCoinOptions!.rechid ? 1 : 0)
                      : Border.all(color: const Color(0xFFEDA47E), width: 0)),
              height: 68.h,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Center(
                      child: Text(
                        coinOptions.rechName ?? '',
                        style: TextStyle(fontSize: 25.sp, color: Colors.white, fontWeight: FontWeight.w600),
                      ),
                    ),
                    Image.asset('assets/app/images/member/wallet_coin.png', width: 19.w),
                    SizedBox(width: 8.w),
                    Container(
                      height: 21.h,
                      padding: const EdgeInsets.only(left: 12, right: 12),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          gradient: const LinearGradient(
                              colors: [Color(0xFFFFD06A), Color(0xFFFFA851)],
                              begin: Alignment.centerRight,
                              end: Alignment.centerLeft),
                          borderRadius: BorderRadius.circular(4)),
                      child: Text(coinOptions.rechExtra ?? '', style: TextStyle(color: Colors.white, fontSize: 13.sp)),
                    ),
                    Expanded(
                      child: Text.rich(
                          textAlign: TextAlign.center,
                          TextSpan(
                              style: TextStyle(fontSize: 20.sp, color: Colors.white, fontWeight: FontWeight.bold),
                              children: [TextSpan(text: '${coinOptions.priceStr}')])),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ).onTap(() {
          chooseCoinOptions = coinOptions;
          setState(() {});
        });
      },
      itemCount: walletConfig?.sec2?.coinOptions?.length,
    );
  }

  // SliverList _buildMemberVipFlagsWarpper() {
  //   return SliverList.builder(
  //     itemBuilder: (BuildContext context, int index) {
  //       VipRights vipRights = walletConfig!.sec3!.vipRights![index];
  //       return Container(
  //         decoration: const BoxDecoration(color: Color(0xFF212121)),
  //         height: 45.h,
  //         child: Container(
  //           padding: EdgeInsets.symmetric(horizontal: 16.w),
  //           child: Row(
  //             mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //             children: [
  //               Text(vipRights.rightName ?? '', style: TextStyle(fontSize: 12.sp, color: Colors.white)),
  //               Text(vipRights.vipDesc ?? '', style: TextStyle(fontSize: 12.sp, color: Colors.white)),
  //               Text(vipRights.unvipDesc ?? '', style: TextStyle(fontSize: 12.sp, color: Colors.white))
  //             ],
  //           ),
  //         ),
  //       );
  //     },
  //     itemCount: walletConfig?.sec3?.vipRights?.length,
  //   );
  // }

  Container _buildMemberInfoWarpper() {
    return Container(
      height: 90,
      padding: EdgeInsets.symmetric(horizontal: 8.w),
      margin: const EdgeInsets.only(bottom: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.symmetric(horizontal: 8.w),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Image.asset('assets/app/images/member/wallet_coin.png', width: 19.w),
                const SizedBox(width: 10),
                Text(walletConfig?.sec1?.coin.toString() ?? '',
                    style: TextStyle(color: Colors.white, fontSize: 28.sp, fontWeight: FontWeight.w600)),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 10.0),
            child: Text(
              walletConfig?.sec1?.title ?? '',
              style: TextStyle(color: Colors.white, fontSize: 14.sp),
            ),
          )
        ],
      ),
    );
  }
}
